package org.javaweb.cms_web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class AttachmentController {

    @GetMapping("/download")
    public void downloadFile(@RequestParam("filePath") String encodedFilePath, HttpServletResponse response) {
        try {
            // 调试信息：查看传入的文件路径
            System.out.println("Encoded file path from request: " + encodedFilePath);

            // 对文件路径进行 URL 解码
            String decodedFilePath = URLDecoder.decode(encodedFilePath, StandardCharsets.UTF_8.name());
            System.out.println("Decoded file path: " + decodedFilePath);

            File file = new File(decodedFilePath);

            // 校验文件是否存在且是文件
            if (!file.exists() || !file.isFile()) {
                System.out.println("File not found: " + decodedFilePath);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在");
                return;
            }

            // 调试信息：查看文件名
            System.out.println("File to download: " + file.getName());

            // 设置响应头，告知浏览器以下载形式处理
            response.setContentType("application/octet-stream");
            String encodedFileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.name());
            System.out.println("Encoded file name for download: " + encodedFileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

            // 输出文件内容
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
                System.out.println("File download completed successfully.");
            }
        } catch (Exception e) {
            System.err.println("Error occurred during file download:");
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
